// 类 + 类方法的形式
const { exec } = require('../db/index')
class UsersService {
  async add(ctx, next) {
    const { username, password, nickname } = ctx.request.body;
    // 先查询
    const queryData = await exec(`select * from users where username=?`, [username])
    if (!queryData.length) {
      const data = await exec(`insert into users (username, password, nickname) values (?,?,?)`, [username, password, nickname])
      if (data.affectedRows) {
        return { code: 0, msg: '数据添加成功', id: data.insertId };
      } else {
        return { code: -1, msg: '数据插入失败' };
      }
    } else {
      return { code: -1, msg: '数据已经存在了' };
    }
  }

  async page(ctx) {
    const { page, size } = ctx.query;
    if (page && size) {
      const total = await exec(`select count(id) as num from users`)
      const data = await exec(`select * from users limit ? offset ?`, [size * 1, page * size])
      return { code: 0, msg: 'success', total: total[0].num, data }
    } else {
      const data = await exec(`select * from users`)
      return { code: 0, msg: 'success', data }
    }
  }
}

module.exports = new UsersService